package proxy.dynamic.v2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class BaseInvocationHandlerProxy<T> implements InvocationHandler {

    private SystemLogService<T> systemLogService;

    private T target;

    BaseInvocationHandlerProxy(SystemLogService systemLogService){
        this.systemLogService = systemLogService;
    }

    public T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        this.target = clazz.newInstance();
        return (T)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        systemLogService.befor(target, x -> System.out.println(x + " befor log...."));
        Object result = method.invoke(target, args);
        systemLogService.after(target, x -> System.out.println(x + " after log...."));
        return result;
    }
}
